import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { Droppable, Draggable, DragDropContextProvider } from '@/plugins/dnd'
import { FixedSizeList as List } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
import { StyledListTop, Wrap } from './style'
import { ListBody, ListTop, ListEmpty, ActionType } from '@/components/List'
import { CreateMemberProps, ListTranslator, RowRendererProps, TerMode } from './interface'
import { ListItem } from './ListItem'
import { DropData } from '@/api/manager/type'
import { UserEntity } from '@/api/create/interface'
import { ListItemGhost } from '../DndGhost'
import { dealDrop, listOrderClick, listToggle } from '@/utils/listSlice'
import { createMemberContext } from './context'
import { t } from 'i18next'

const rowRenderer = React.memo(({ data: list, index, style }: RowRendererProps) => {
	const rowData = list[index]
	const dataTransfer = () => {
		return {
			data: {
				mt: rowData.mcc,
			},
			from: 'list-item',
		}
	}
	return (
		<Draggable
			style={style}
			index={index}
			dataTransfer={dataTransfer}
			ghostRender={<ListItemGhost data={rowData.mcc} />}
		>
			<ListItem {...rowData} />
		</Draggable>
	)
})

const CreateMember = (props: CreateMemberProps) => {
	const isShowBottomTip = props.isShowBottomTip ?? true
	const [list, setList] = useState(ListTranslator(props.list || []))
	useEffect(() => {
		setList((preList) => {
			let cur = ListTranslator(props.list || [])
			return cur.map((c) => {
				let p = preList.find((pre) => pre.uuid === c.uuid)
				if (p) c.status.checked = p.status.checked
				return c
			})
		})
	}, [props.list])

	const setOuterList = (l: TerMode[], type: 'remove' | 'sort' | 'drop') =>
		props.setOuterList(
			l.map((x) => x.mcc),
			type
		)

	const topActions = props.topActions
		? props.topActions
		: [
				{
					text: t('删除'),
					onClick: () => {
						if (props.disabled) return
						const unCheckedList = list.filter((x) => !x.status.checked)
						setOuterList(unCheckedList, 'remove')
					},
				},
				{
					text: t('清空'),
					onClick: () => {
						if (props.disabled) return
						setOuterList([], 'remove')
					},
				},
		  ]

	const handleDrop = (dataTransfer: DropData<UserEntity>, index: number) => {
		if (props.disabled) return
		let mt = dataTransfer?.data?.mt
		if (mt) {
			const result = dealDrop(
				list,
				{
					mts: ListTranslator([mt]),
					isOther: dataTransfer.from !== 'list-item',
					dropIndex: index,
				},
				'uuid'
			)
			setOuterList(result, dataTransfer.from !== 'list-item' ? 'drop' : 'sort')
		}
	}

	const handleOrder = async (type: ActionType) => {
		if (!props.disabled) {
			let flag = true
			if (type === 'top') {
				if (props.top) {
					flag = await props.top()
				}
			}
			if (type === 'up') {
				if (props.up) {
					flag = await props.up()
				}
			}
			if (type === 'down') {
				if (props.down) {
					flag = await props.down()
				}
			}
			if (type === 'bottom') {
				if (props.bottom) {
					flag = await props.bottom()
				}
			}
			if (flag) {
				const result = listOrderClick(list, type)
				setOuterList(result, 'sort')
			}
		}
	}

	const _start = useRef<string | null>(null)
	const _changes = useRef<string[]>([])
	const itemHandle = (uuid: string, type: 'click' | 'remove' | 'ctrl' | 'shift') => {
		if (props.disabled) return
		if (type === 'remove') {
			let result = list.filter((x) => x.uuid !== uuid)
			setOuterList(result, 'remove')
		} else {
			const result = listToggle(
				list,
				{
					_start: _start.current,
					_changes: _changes.current,
					action: type,
					path: 'uuid',
				},
				uuid
			)
			setList(result.list)
			_start.current = result._start
			_changes.current = result._changes
		}
	}

	return (
		<Wrap height={props.height} width={props.width}>
			{props.disabled && <div className="mask"></div>}
			<StyledListTop>
				{typeof props.title === 'string' || typeof props.title === 'undefined' ? (
					<ListTop title={props.title || t('已选')} actions={topActions} num={list.length}></ListTop>
				) : (
					<ListTop actions={topActions}>{props.title}</ListTop>
				)}
			</StyledListTop>
			{props.children}
			<ListBody
				order={handleOrder}
				disabled={props.disabled || list.length === 0}
				isHideOrder={!!props.isHideOrder}
				_height={45}
			>
				<AutoSizer>
					{({ width, height }) => (
						<DragDropContextProvider>
							<Droppable onDrop={handleDrop} placeholderHeight={42}>
								{(setDroppableRef) =>
									list.length > 0 ? (
										<createMemberContext.Provider value={itemHandle}>
											<List
												width={width - 40}
												height={height}
												itemCount={list.length}
												itemSize={38}
												itemData={list}
												itemKey={(index, data) => data[index].uuid}
												outerRef={setDroppableRef}
											>
												{rowRenderer}
											</List>
										</createMemberContext.Provider>
									) : (
										<ListEmpty width={width - 40} height={height} outerRef={setDroppableRef} />
									)
								}
							</Droppable>
						</DragDropContextProvider>
					)}
				</AutoSizer>
			</ListBody>
			<div className="seperate"></div>
			{isShowBottomTip && (
				<div className="member_tip">
					<p>{t('可使用ctrl或shift快捷键进行多选')}</p>
				</div>
			)}
		</Wrap>
	)
}

export default CreateMember
